import { BellOutlined, UserOutlined } from '@ant-design/icons';
import { Avatar, Badge, Button, Divider, List, message, Popover, Skeleton } from 'antd';
import Cookies from 'js-cookie';
import { useEffect, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import { history } from 'umi';

import type { FC, ReactNode } from 'react';

import { getMsgDatas, setMsgStatus } from '@/services/msg';
import type { msgParams } from '@/services/msg';

import styles from './index.less';
let timer: any = null;
const MsgPop: FC = () => {
  const [tableData, setTableData] = useState<msgParams[]>([]);
  const getTableData = async () => {
    try {
      await getMsgDatas({ isRead: false }).then((res) => {
        if (res && res.code === 200) {
          const dataReverseCopy = res.data;
          dataReverseCopy.reverse();
          setTableData(dataReverseCopy);
          clearInterval(timer);
          timer = setInterval(() => {
            getTableData();
          }, 20000);
        }
      });
    } catch (error) {
      message.error(String(error));
    } finally {
    }
  };

  const getHistory = () => {
    if (location.pathname === '/') window.open('PersonCenter/?status=4');
    else history.replace('/PersonCenter/?status=4');
  };
  const changeStatus = async () => {
    const array: string[] = [];
    tableData.forEach((item) => {
      array.push(item.id);
    });
    await setMsgStatus(array)
      .then((res) => {
        if (res && res.code === 200) {
          message.success('设置成功！');
          clearInterval(timer);
          getTableData();
        } else {
          message.error(res.message);
        }
      })
      .catch((res) => message.error(res));
  };
  const titleContent: ReactNode = (
    <div style={{ display: 'flex', width: '100%' }}>
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          width: 'calc( 100% - 112px )',
          fontSize: 16,
          fontFamily: 'Source Han Sans CN',
          fontWeight: 'bold',
          color: '#000000',
        }}
      >
        消息通知
      </div>
      <div style={{ display: 'flex', alignItems: 'center', width: 112 }}>
        <Button
          type="link"
          style={{
            marginRight: 4,
            width: 48,
            fontSize: 12,
            fontFamily: 'PingFangSC-Regular',
            color: '#1A3DC9',
          }}
          onClick={getHistory}
        >
          查看历史
        </Button>
        <Button
          type="link"
          style={{
            marginLeft: 4,
            width: 48,
            fontSize: 12,
            fontFamily: 'PingFangSC-Regular',
            color: '#1A3DC9',
          }}
          onClick={changeStatus}
        >
          全部已读
        </Button>
      </div>
    </div>
  );

  const popContent: ReactNode = (
    <div
      id="scrollableDiv"
      style={{
        maxHeight: 622,
        overflow: 'auto',
      }}
    >
      <InfiniteScroll
        dataLength={tableData.length}
        hasMore={false}
        next={changeStatus}
        loader={<Skeleton avatar paragraph={{ rows: 1 }} active />}
        endMessage={<Divider plain>暂无更多</Divider>}
        scrollableTarget="scrollableDiv"
      >
        <List
          itemLayout="horizontal"
          dataSource={tableData}
          size="small"
          renderItem={(item) => (
            <List.Item>
              <List.Item.Meta
                avatar={<Avatar icon={<UserOutlined />} />}
                title={<a>{item.createUserName}</a>}
                description={
                  <div>
                    <div>{item.content || ''}</div>
                    <div>{item.createTime || ''}</div>
                  </div>
                }
              />
            </List.Item>
          )}
        />
      </InfiniteScroll>
    </div>
  );

  useEffect(() => {
    if (Cookies.get('saas_token')) getTableData();
    return () => {
      clearInterval(timer);
    };
  }, []);
  return (
    <Popover
      content={popContent}
      placement="bottom"
      overlayStyle={{ width: 350 }}
      title={titleContent}
    >
      <div className={styles.iconStyle1}>
        {tableData.length ? (
          <Badge dot>
            <Avatar
              style={{ color: '#333', background: '#fff', width: 18 }}
              icon={<BellOutlined />}
            />
          </Badge>
        ) : (
          <BellOutlined />
        )}
      </div>
    </Popover>
  );
};
export default MsgPop;
